// 封装全局请求方法
export const baseUrl = 'http://192.168.31.45:8080'

export const request = (options) => {
  // 获取本地存储的token
  const token = uni.getStorageSync('token')
  
  // 设置默认请求头
  const header = {
    'Content-Type': 'application/x-www-form-urlencoded',
    ...options.header
  }
  
  // 如果有token，添加到请求头
  if (token) {
    header['Authorization'] = `Bearer ${token}`
  }
  // console.log("封装的内容：",options);
  
  return new Promise((resolve, reject) => {
		console.log("执行：",options.url);
    uni.request({
      url: baseUrl + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header,
      success: (res) => {
        // 响应拦截处理
        if (res.statusCode === 200 || res.status  === 200) {
					console.log(options.url,"成功处理");
          resolve(res.data)
        } else if (res.statusCode === 403 || res.status  === 403) {
          // Token过期处理
					console.log("Token过期");
					setTimeout(()=>{
						uni.navigateTo({
							url: '/pages/starter/login/login'
						})
						uni.showToast({
							title: '登录已过期，请重新登录',
							icon: 'none'
						})						
					},0)
          
          reject(res)
        } else {
					console.log("其他错误");
          uni.showToast({
            title: res.data.message || '请求失败',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 封装常用方法
export const http = {
  get(url, data, options = {}) {
    return request({
      url,
      method: 'GET',
      data,
      ...options
    })
  },
  post(url, data, options = {}) {
    return request({
      url,
      method: 'POST',
      data,
      ...options
    })
  },
  put(url, data, options = {}) {
    return request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  },
  delete(url, data, options = {}) {
    return request({
      url,
      method: 'DELETE',
      data,
      ...options
    })
  }
}
